﻿#ifndef _SCRIPTMANAGER_H_INCLUDE_
#define _SCRIPTMANAGER_H_INCLUDE_

#include "common.h"
#include <wx/vector.h>
#include <string>
#include <mutex>

class CMainFrame;
class maindrawscene;
class WNodeManager;
class WBaseNode;

class ScriptManager : public Singleton<ScriptManager>
{
public:
    ScriptManager();
    ~ScriptManager();

    /// 初始化
    bool lua_init();
    /// 退出
    void lua_exit();
    /// 得到luastate
    inline lua_State* get_luastate(void) { return m_lua_state; }
    /// 注册到lua
    void registertoLua(void);
    /// 导入指定目录所有脚本并执行
    bool exe_lua_string_for_path(wxString scriptPath);
    /// 导入指定文件脚本并执行
    bool exe_lua_string_for_file(wxString scriptFile);
    /// 重置系统
    bool CreateIsolatedLuaEnvironment(bool inheritGlobals=false);

    /// 注册结点到lua中
    void registerBaseNodetoLua(wxString nodeType,WBaseNode* basenode);
    /// 注册结点管理器到lua中
    void registerNodeManagertoLua(WNodeManager *manager);
    /// 注册主窗口到lua中
    void registerMainFrametoLua(CMainFrame *mainframe);

    /// 调用lua主绘制接口
    void callLuaFunctionWithMainDrawScene(maindrawscene *pmaindrawscene);
    /// 调用lua系统初始接口
    void callLuaFunctionWithSystemInit(void);
    /// 调用lua系统更新接口
    void callLuaFuncitonWithSystemUpdate(void);
    /// 调用lua系统鼠标事件接口
    void callLuaFunctionWithSystemMouseEvent(wxMouseEvent& event);

    /// 调用网络连接建立成功接口
    void callLuaFunctionWithNetworkConnected(const char *clientid);
    /// 调用服务器消息到达接口
    void callLuaFunctionWithServerMessageCome(const char* clientid,int msgType,const char* message,int msglength);

    /// 调用结点的鼠标事件接口
    void callLuaFunctionWithBaseNodeMouseEvent(wxString nodeName,wxMouseEvent& event);
    /// 调用结点的更新接口
    void callLuaFunctionWithBaseNodeUpdate(wxString nodeName);
    /// 调用结点的绘制接口
    void callLuaFunctionWithBaseNodeDraw(maindrawscene *pmaindrawscene,wxString nodeName);

private:
    /// 执行脚本
    bool exe_lua_string(wxMemoryBuffer& buffer,wxString filename="");
    /// 注册主绘图到脚本
    void registermaindrawsceneToLua(void);
    /// 注册wxWidgets到脚本
    void registerwxWidgetsToLua(void);
    /// 注册系统函数到脚本中
    void registerSystemFunToLua(void);
    /// 注册结点到脚本中
    void registerNodeToLua(void);
    /// 注册STL到脚本中
    void registerSTLToLua(void);

private:
    template <typename T> void registerVector(lua_State* L, const std::string& className);

private:
    lua_State* m_lua_state;
    std::mutex m_luastateMutex;
};

#endif // SCRIPTMANAGER_H
